package cn.edu.scau.vsac.controller;

import cn.edu.scau.vsac.annotation.LoginRequired;
import cn.edu.scau.vsac.common.ResultData;
import cn.edu.scau.vsac.entity.HelpOffer;
import cn.edu.scau.vsac.entity.HelpRequest;
import cn.edu.scau.vsac.entity.User;
import cn.edu.scau.vsac.service.HelpOfferService;
import cn.edu.scau.vsac.service.HelpRequestService;
import cn.edu.scau.vsac.service.UserService;
import cn.edu.scau.vsac.util.HostHolder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Tag(name = "用户")
public class UserController {

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private UserService userService;

    @Autowired
    private HelpOfferService helpOfferService;

    @Autowired
    private HelpRequestService helpRequestService;

    @RequestMapping(path = "/modify", method = RequestMethod.POST)
    @Operation(summary = "modify")
    public ResultData<Boolean> modifyInfo(String password, String sex, String info) {
        User user = hostHolder.getUser();
        if (password != null && password.length() > 0) {
            user.setPassword(password);
        }
        if (sex != null && sex.length() > 0) {
            user.setSex(sex);
        }
        if (info != null && info.length() > 0) {
            user.setInfo(info);
        }
        userService.updateById(user);
        return ResultData.success(true);
    }

    @LoginRequired
    @RequestMapping(path = "/profile", method = RequestMethod.GET)
    @Operation(summary = "profile")
    public ResultData<Map<String, Object>> getProfilePage(Model model) {
        Map<String, Object> map = new HashMap<>();
        User user = hostHolder.getUser();
        model.addAttribute("user", user);
        map.put("user", user);

        QueryWrapper<HelpRequest> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getUserId());
        List<HelpRequest> helpRequests = helpRequestService.list(queryWrapper);
        model.addAttribute("helpRequests", helpRequests);
        map.put("helpRequests", helpRequests);

        QueryWrapper<HelpOffer> queryWrapper1 = new QueryWrapper<>();
        queryWrapper.eq("helper_id", user.getUserId());
        List<HelpOffer> helpOffers = helpOfferService.list(queryWrapper1);
        model.addAttribute("helpOffers", helpOffers);
        map.put("helpOffers", helpOffers);

        return ResultData.success(map);
    }

}
